package com.xyht.sca_s.student_manage_system.auth.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.visitor.entity.SmsVisitorUser;
import com.xyht.sca_s.student_manage_system.modules.visitor.mapper.SmsVisitorUserMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JwtToken生成的工具类
 * JWT token的格式：header.payload.signature
 * header的格式（算法、token的类型）：
 * {"alg": "HS512","typ": "JWT"}
 * payload的格式（用户名、创建时间、生成时间）：
 * {"sub":"wang","created":1489079981393,"exp":1489684781}
 * signature的生成算法：
 * HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
 * Created by macro on 2018/4/26.
 */
@Component
public class JwtTokenUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    private static final int REFRESH_TIME = 60 * 40;
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;
    @Value("${jwt.tokenHead}")
    public String tokenHead;
    @Value("${jwt.tokenHeader}")
    public String tokenHeader;

    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private SmsVisitorUserMapper smsVisitorUserMapper;

    /**
     * 根据负责生成JWT的token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            LOGGER.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    private Claims getClaimsFromToken(String token,String secret) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            LOGGER.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }


    /**
     * 从token中获取登录用户ID
     */
    public String getUserIdFromToken(String token) {
        String id;
        try {
            Claims claims = getClaimsFromToken(token);
            id = claims.getSubject();
        } catch (Exception e) {
            id = null;
        }
        return id;
    }

    public String getUserIdFromTokenSecret(String token,String secret) {
        String id;
        try {
            Claims claims = getClaimsFromToken(token,secret);
            id = claims.getSubject();
        } catch (Exception e) {
            id = null;
        }
        return id;
    }

    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     */

    @Autowired
    private SmsUserMapper smsUserMapper;

    public boolean validateToken(String token) {
        String username = getUserIdFromToken(token);
        if (username == null) {
            return false;
        }
        if (isTokenExpired(token)) {
            return false;
        }
        SmsUser smsUser = cacheUtil.getUserInfo(username);
        if (smsUser == null) {
//            cacheUtil.saveUserInfo(username);
//            smsUser = cacheUtil.getUserInfo(username);
//            if (smsUser == null){
            return false;
//            }
        }
        return true;
    }

    public boolean validateVisitorToken(String token) {
        String username = getUserIdFromToken(token);
        if (username == null) {
            return false;
        }
        if (isTokenExpired(token)) {
            return false;
        }
        SmsVisitorUser smsUser = cacheUtil.getVisitorUserInfo(username);
        if (smsUser == null) {
//            cacheUtil.saveUserInfo(username);
//            smsUser = cacheUtil.getUserInfo(username);
//            if (smsUser == null){
            return false;
//            }
        }
        return true;
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 根据用户信息生成token
     */
    public String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, username);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * 当原来的token没过期时是可以刷新的
     *
     * @param oldToken 带tokenHead的token
     */
    public String refreshHeadToken(String oldToken) {
        if (StrUtil.isEmpty(oldToken)) {
            return null;
        }
        //token校验不通过
        Claims claims = getClaimsFromToken(oldToken);
        if (claims == null) {
            return null;
        }
        //如果token已经过期，不支持刷新
        if (isTokenExpired(oldToken)) {
            return null;
        }
        //如果token在40分钟之内刚刷新过，返回原token
        if (tokenRefreshJustBefore(oldToken)) {
            return oldToken;
        } else {
            claims.put(CLAIM_KEY_CREATED, new Date());
            return generateToken(claims);
        }
    }

    /**
     * 判断token在指定时间内是否刚刚刷新过
     *
     * @param token 原token
     */
    public boolean tokenRefreshJustBefore(String token) {
        Claims claims = getClaimsFromToken(token);
        Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
        Date refreshDate = new Date();
        //刷新时间在创建时间的指定时间内
        if (refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, REFRESH_TIME))) {
            return true;
        }
        return false;
    }

    /**
     * @param request 请求request
     */
    public String getUserIdByRequest(HttpServletRequest request) {
        //http的header中获得token
        String token = request.getHeader(tokenHeader);
        //token不存在
        if (token == null || token.equals("")) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.UNAUTHORIZED));
        }
        //验证token
        String authToken = token.substring(tokenHead.length());
        String user_id = getUserIdFromToken(authToken);
        if (user_id == null) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        return user_id;
    }

    public String getVisitorUserIdByRequest(HttpServletRequest request) {
        //http的header中获得token
        String token = request.getHeader(tokenHeader);
        //token不存在
        if (token == null || token.equals("")) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.UNAUTHORIZED));
        }
        //验证token
        String authToken = token.substring(tokenHead.length());
        String user_id = getUserIdFromToken(authToken);
        if (user_id == null) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        return user_id;
    }

}
